//
//  SaveTools.swift
//  GifUsage
//
//  Created by han on 2021/4/14.
//  Copyright © 2021 Ting Han. All rights reserved.
//

import UIKit
import Photos
import ImageIO
import MobileCoreServices

struct SaveTools {
    static func saveGIF(_ path: String) {
        // 保存GIF需要通过URL来保存
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: URL(fileURLWithPath: path))
        }, completionHandler: {success, error in
            if !success { print("error creating asset: \(String(describing: error))") }
        })
    }
    
    static func saveImage(_ image: UIImage) {
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAsset(from: image)
        }, completionHandler: {success, error in
            if !success { print("error creating asset: \(String(describing: error))") }
        })
    }
    
    static func saveLivePhotoToAlbum(_ photoPath: String, _ videoPath: String) {
        // LivePhoto包含两个部分，一部分是一张jpg图片，一部分则是一个mov视频
        let photoURL = URL(fileURLWithPath: photoPath) // .jpg
        let videoURL = URL(fileURLWithPath: videoPath) // .mov
        
        PHPhotoLibrary.shared().performChanges {
            let request = PHAssetCreationRequest()
            request.addResource(with: .photo, fileURL: photoURL, options: nil)
            request.addResource(with: .pairedVideo, fileURL: videoURL, options: nil)
        } completionHandler: { (success, error) in
            if success {
                print("save livePhoto success")
            } else {
                print("save livePhoto error: \(String(describing: error))")
            }
        }
    }
    
    static func saveImageWrite(_ image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, nil, nil)
    }
}
